﻿using System;
using System.Collections.Generic;
using System.IO;

namespace Spellchecker {
    public class Spellchecker {

        public static bool HasSpellingErrors(string text) {
            string cleanText = ClearText(text);
            IEnumerable<string> wordsList = SplitIntoWords(cleanText);
            Dictionary<string, string> dict = Load("wortverzeichnis.txt");
            return !CheckWords(wordsList, dict);
        }

        internal static string ClearText(string text) {
            string[] trenner = {".",",",";","!","?",":","'","\"","\t","\n","\r" };
            if (String.IsNullOrEmpty(text)) {
                return String.Empty;
            }
            foreach (var c in trenner) {
                text = text.Replace(c, " ");
            }
            return text;
        }

        internal static IEnumerable<string> SplitIntoWords(string text) {
            string[] leerzeichen = {" "};
            return text.Split(leerzeichen,StringSplitOptions.RemoveEmptyEntries);
        }

        internal static bool CheckWords(IEnumerable<string> textToTest, Dictionary<string, string> wortverzeichnis) {
            bool isInWortverzeichnis = true;
            foreach (var toTest in textToTest) {
                if (!wortverzeichnis.ContainsKey(toTest.ToLower())) {
                    isInWortverzeichnis = false;
                    break;
                }
            }
           return isInWortverzeichnis;
        }

        internal static Dictionary<string,string> Load(string fileName) {
            var dict = new Dictionary<string, string>();
            string [] dictArray = File.ReadAllLines(fileName);

            foreach (var s in dictArray) {
                dict.Add(s.ToLower(),"");
            }
            return dict;
        }
    }
}
